<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" style="height: 100%;">

<head>
  <meta name="viewport" content="width=device-width, minimum-scale=0.1">
  <title th:text="${title}">图片查看器</title>
</head>

<body style="margin: 0px; background: #0e0e0e; height: 100%; text-align: center; align-items: center;">
  <input id="length" type="hidden" value="99" th:value="${length}" />
  <input id="page" type="hidden" value="1" th:value="${page}" />
  <input id="url" type="hidden" value="" th:value="${url}" />

  <div style="width: 100%; height: 100%;">
    <img id="image" style="-webkit-user-select: none;margin: auto;cursor: zoom-in;background-color: hsl(0, 0%, 90%);
      transition: background-color 300ms; cursor:default; " th:src="${url+'/1'}" title="方向键切换/点击左右两边" height="100%"
      onload="checkImage()" onerror="checkImage()">
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
    let title = document.title;
    let length = parseInt($("#length").val());
    let page = parseInt($("#page").val());

    let url = $("#url").val();
    let urls = url.split("/");
    let uuid = urls[urls.length - 1];
    
    let $image = $("#image");
    
    if (page == 0) {
      page = localStorage.getItem(uuid);
      if (page == null) {
        page = 1;
      } else {
        page = parseInt(page);
      }
    }
    
    let flag = true;
    function init() {
      let src = url + "/" + page;
      $image.attr("src", src);
      document.title = page + " / " + length + " - " + title;
      localStorage.setItem(uuid, page);
    }

    function checkImage() {
      let r1 = $image.height() / $image.width();
      let r2 = $image.parent().height() / $image.parent().width();
      if (r1 < r2) {
        $image.height("auto");
        $image.width("100%");
      } else {
        $image.height("100%");
        $image.width("auto");
      }
      flag = true;
    }
    function last() {
      if (!flag) {
        return;
      }
      flag = false;
      if (page == 1) {
	  	page = length;
	  } else {
		page -= 1;
	  }
      init();
    }
    function next() {
      if (!flag) {
        return;
      }
      flag = false;
      if (page == length) {
        page = 1;
      } else {
        page += 1;
      }
      init();
    }
    let date = new Date();
    let lastTime = date.getTime();
    $(document).keydown(function(event){
		date = new Date();
		var time = date.getTime();
		if (time - lastTime > 100) {
			lastTime = time;
			if (event.keyCode == 39) {
		        next();
		      } else if (event.keyCode == 37) {
		        last();
		      }
		}
	});
    $image.click(event => {
      if (event.offsetX < $image.width() / 2) {
        last();
      } else {
        next();
      }
    });
    init();
  </script>
</body>

</html>